package com.leaf.spring.y201906.day25.arithmetic.random;

import java.util.Random;

import com.leaf.spring.y201906.day25.arithmetic.ServerIps;

/**
 * 随机+权重算法实现负载均衡 <br/>
 * 
 * 按照顺序将权重值依次平铺在一维坐标上， 根据坐标区间获取对应的服务
 * 
 * {A, 2;B, 3;C 5} <br/>
 * 0-2--5----10 <br/>
 * [0,2) -> A 
 * [2,5) -> B 
 * [5,10) -> C
 * 
 * @Title:
 * @Description:
 * @Author: leaf
 * @Since:2019年6月25日
 * @Version:1.2.0
 */
public class WeightRandomArithV2 {

	public String getServer() {

		int totalWeight = 0; // 总权重值
		boolean sameWeight = true; // 如果所有权重值都相等，则随机一个服务就可以了

		Object[] weights = ServerIps.WEIGHT_LIST.values().toArray();

		for (int i = 0; i < weights.length; i++) {

			Integer weight = (Integer) weights[i];
			totalWeight += weight;

			if (sameWeight && i > 0 && !weight.equals(weights[i - 1])) {
				sameWeight = false;
			}
		}

		Random random = new Random();
		int pos = random.nextInt(totalWeight);

		// 权重值不相等
		if (!sameWeight) {

			for (String server : ServerIps.WEIGHT_LIST.keySet()) {

				int weight = ServerIps.WEIGHT_LIST.get(server);

				// 将当前key的权重weight与pos比较，
				// 若weight大于pos，则说明pos在当前weight内
				// 若weight小于pos，则将pos移动weight位
				if (weight > pos) {
					return server;
				}
				pos = pos - weight;

			}
		}

		return (String) ServerIps.WEIGHT_LIST.keySet().toArray()[new Random().nextInt(ServerIps.WEIGHT_LIST.size())];

	}

	public static void main(String[] args) {

		WeightRandomArithV2 arith = new WeightRandomArithV2();

		for (int i = 0; i < 10; i++) {
			System.out.println(arith.getServer());
		}

	}

}
